import 'package:FineArt/core/api/course_api.dart';
import 'package:FineArt/core/http/auth_interceptor.dart';
import 'package:FineArt/core/http/base_dio.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'dart:io';

import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import 'package:package_info/package_info.dart';

class PlatformUtil {
  static final platform = const MethodChannel('com.yunhe.fineart/platform');

  static Future<String> uuid(String name) async {
    if (Platform.isIOS) return name;

    try {
      return await platform.invokeMethod('uuid');
    } on PlatformException catch (e) {}

    return "";
  }

  static Future<String> getVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String versionName = packageInfo.version + "." + packageInfo.buildNumber;
    return versionName;
  }

  static Future<int> operationResult(int result) async {
    return result;
  }

  static Dio _dio = null;

  static Dio getDio() {

    if (_dio != null) return _dio;

    _dio = Dio();
    _dio.options = BaseOptions(
        receiveTimeout: 66000, connectTimeout: 66000); // 设置超时时间等 ...
    _dio.interceptors.add(AuthInterceptor()); // 添加拦截器，如 token之类，需要全局使用的参数
    /*_dio.interceptors.add(PrettyDioLogger(
      // 添加日志格式化工具类
      requestHeader: true,
      requestBody: true,
      responseBody: true,
      responseHeader: false,
      compact: false,
    ));*/
    return _dio;
  }

  static Future<void> startCourse(String url, int courseid) async {
    try {
      platform.setMethodCallHandler((call) async {
        if (call.method == "courseOperation") {

          if (call.arguments["oper"] == "finishcourse")
            {
              OperationResponse response = await CourseApi().delete();
              return operationResult(response.code);
            }

          SimpleOperation operation = new SimpleOperation(
              oper: call.arguments["oper"], value: call.arguments["value"]);
          OperationResponse response = await CourseApi(dio: getDio()).operate(courseid,operation);
          return operationResult(response.code);
        }
      });

      await platform.invokeMethod('start_course', {"url": url});
    } on PlatformException catch (e) {}
  }

  static Future<void> showHdImage(String url) async {
    try {
      await platform.invokeMethod('hdimage', {"url": url});
    } on PlatformException catch (e) {}
  }
}
